from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .serializers import *
from .models import *
from django.contrib.auth.models import Group
from guardian.shortcuts import assign_perm, get_perms
from rest_framework.views import Response
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from rest_framework.permissions import IsAuthenticated, IsAdminUser

# Create your views here.


class UserCommentsViewSet(ModelViewSet):


    queryset = UserComments.objects.all()
    serializer_class = UserCommentsSerializer
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (IsAuthenticated, )

    def get_queryset(self):
        if self.action in ('retrieve', 'list'):
            ser = self.get_serializer_class()
            return ser.Meta.model.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        user = self.request.user
        group = Group.objects.get_or_create(name='test')[0]
        # 在创建这篇帖子的时候,授予权限
        # 然后再在做操作的时候,查看验证有木有这个权限
        instance = serializer.save()
        assign_perm('change_usercomments', user, instance)
        assign_perm('delete_usercomments', user, instance)
        assign_perm('delete_usercomments', group, instance)

    def perform_destroy(self, instance):
        permissions = get_perms(self.request.user, instance)
        if 'delete_usercomments' not in permissions:
            raise serializers.ValidationError('你没有权限去删除')
        return super().perform_destroy(instance)

    def perform_update(self, serializer):
        user = self.request.user
        permissions = get_perms(user, serializer.instance)
        if 'change_usercomments' not in permissions:
            raise serializers.ValidationError('你没有权限去更改')
        serializer.save()
        return super().perform_update(serializer)



# class UserCreatePlaylistViewset(ModelViewSet):
#     queryset = UserCreatePlaylist.objects.all()
#     serializer_class = UserCreatePlaylistSerializer

